package cn.itcast.bos.realm;



// 自定义Realm ，实现安全数据 连接


import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class BosRealm  extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;    //角色

    @Autowired
    private PermissionService permissionService;    //权限


    //授权管理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权管理");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        //获取登录的用户，根据用户的姓名查询用户的角色和权限
        User user = (User) subject.getPrincipal();

        List<Role> roles = roleService.findByUser(user);
        for (Role role : roles) {
            authorizationInfo.addRole(role.getKeyword());
        }

        List<Permission> permissions = permissionService.findByUser(user);
        for (Permission permission : permissions) {
            authorizationInfo.addStringPermission(permission.getKeyword());
        }
        return authorizationInfo;
    }


    //认证管理
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("shiro认证管理.....");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //调用方法查询用户名和密码（token内）是否正确
        User user = userService.findByUsername(token.getUsername());
        if (user==null){
            //用户名不存在，返回null
            return null;
        }else {
            /**
             * 用户名存在，返回SimpleAuthenticationInfo对象
             * 1.携带从数据库查询出来的用户信息
             * 2.携带用户输入的密码
             * 3.携带本realm名
             * 注：realm会自动去比较从数据库查询出来的密码和用户输入的密码是否一致
             */
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
    }
}
